﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_F4Export : Form
    {
        private List<string> serialList;
        private List<string> selectedSerial;        
        public frm_F4Export()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            serialList = new List<string>();
            selectedSerial = new List<string>();            
            this.addDate.EditValue = DateTime.Now.Date;
            getCompIDList();
            this.compID.Properties.AutoComplete = true;
            getCheckerList();
            this.staffID.Properties.AutoComplete = true;
            getCustomerList();
            this.customerID.Properties.AutoComplete = true;
            this.compID.SelectedIndexChanged += compID_SelectedIndexChanged;
        }
        
        /////////////////////////////////////
        /// When Change Comp ID
        /////////////////////////////////////
        void compID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.compID.SelectedIndex > -1)
            {                
                getSerialList();                
            }
        }
        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getCompIDList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DISTINCT CompID AS CompID"
                    + " FROM [231_RobotOrderDetail] WHERE Exported=0 ORDER BY CompID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {                    
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CompID"].ToString();                    
                    item.Value = dataReader["CompID"].ToString();
                    this.compID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Comp list");
            }
        }


        ////////////////////////////////////////////////
        /// Load Customer list to combobox
        ////////////////////////////////////////////////
        private void getCustomerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString() + " | " + dataReader["FullName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Customer list");
            }
        } 

        ////////////////////////////////////////////////
        /// Load Staff list to Export By combobox
        ////////////////////////////////////////////////
        private void getCheckerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName"
                    + " FROM [222_Staff] WHERE StopDate IS NULL ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString() + " | " + dataReader["StaffID"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.staffID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Staff list");
            }
        } 

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            DateTime exporteddate;
            string comp = null;            
            int selected_quantity = 0;
            int total_quantity = 0;
            string export_by = null;
            string customer = null;
            
            ComboboxItem item = new ComboboxItem();

            if (!DateTime.TryParse(this.addDate.DateTime.Date.ToString(), out exporteddate))
            {
                error = "Please select Export Date";
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.compID.SelectedIndex < 0)
                {
                    error = "Please Select CompID";
                }
                else
                {
                    item = (ComboboxItem)this.compID.SelectedItem;
                    comp = item.Value.ToString();
                }
            }

            total_quantity = this.serialList.Count;
            selected_quantity = this.selectedSerial.Count;            

            if (string.IsNullOrEmpty(error))
            {
                if (selected_quantity <= 0)
                {
                    error = "Please select at least one serial number";
                }                
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.staffID.SelectedIndex < 0)
                {
                    error = "Please Select Checker.";
                }
                else
                {
                    item = (ComboboxItem)this.staffID.SelectedItem;
                    export_by = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.customerID.SelectedIndex < 0)
                {
                    error = "Please Select Checker.";
                }
                else
                {
                    item = (ComboboxItem)this.customerID.SelectedItem;
                    customer = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                string serial = null;
                string[] temp = selectedSerial.ToArray();
                for (int i = 0; i < temp.Length; i++)
                {
                    temp[i] = "'" + temp[i] + "'";
                }
                serial = string.Join(",", temp);
                
                try
                {
                    myConnection.Open();
                    string sql = "UPDATE [231_RobotOrderDetail] SET Exported=1, ExportedDate=@exporteddate,"
                        + " ExportedBy='" + export_by + "', CustomerID='" + customer + "'"
                        + " WHERE (CompID=N'" + comp + "') AND (SerialNo IN (" + serial + "))";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@exporteddate", SqlDbType.DateTime).Value = exporteddate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    getSerialList();                    
                    
                    MessageBox.Show("F4 Export success.");
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot add F4 Export Trouble. Please try again.");
                }                 
            }
            else
            {
                MessageBox.Show(error);
            }
        }        
       
        /////////////////////////////////////////////////
        /// Create Serial No List with selected Order No
        /////////////////////////////////////////////////
        private void getSerialList()
        {
            serialList.Clear();
            serialNo.DataSource = null;
            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;
            this.serialNo.Enabled = true;
            this.selectedSerialNo.Enabled = true;
            this.buttonSelectAll.Enabled = true;
            this.buttonSelect.Enabled = true;
            this.buttonDeselect.Enabled = true;
            this.buttonDeselectAll.Enabled = true;
            this.troubleQty.Enabled = false;
            this.buttonAdd.Enabled = true;
            
            ComboboxItem comp = (ComboboxItem)this.compID.SelectedItem;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SerialNo FROM [231_RobotOrderDetail]"
                    + " WHERE (CompID='" + comp.Value + "')"
                    + " AND (Exported=0) AND (Finished=1)";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    serialList.Add(dataReader["SerialNo"].ToString());                    
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();

                serialNo.DataSource = serialList;
                quantityValue.Text = serialList.Count.ToString();
                troubleQty.Text = "0";
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
            }

            this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();

            if (this.serialList.Count == 0)
            {
                this.serialNo.Enabled = false;
                this.selectedSerialNo.Enabled = false;
                this.buttonSelectAll.Enabled = false;
                this.buttonSelect.Enabled = false;
                this.buttonDeselect.Enabled = false;
                this.buttonDeselectAll.Enabled = false;

                this.buttonAdd.Enabled = false;
            }
        }

        ////////////////////////////
        /// Select All Serial
        ////////////////////////////
        private void buttonSelectAll_Click(object sender, EventArgs e)
        {            
            foreach (string value in serialList)
            {
                selectedSerial.Add(value);
            }
            //selectedSerial = serialList;
            selectedSerialNo.DataSource = null;
            selectedSerial.Sort();
            selectedSerialNo.DataSource = selectedSerial;

            serialList.Clear();
            serialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }

        /////////////////////////////////////
        /// Deselect all serial
        ////////////////////////////////////
        private void buttonDeselectAll_Click(object sender, EventArgs e)
        {
            foreach (string value in selectedSerial)
            {
                serialList.Add(value);
            }
            //selectedSerial = serialList;
            serialNo.DataSource = null;
            serialList.Sort();
            serialNo.DataSource = serialList;

            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }
        
        /////////////////////////////
        /// Select some serial
        /////////////////////////////
        
        private void buttonSelect_Click(object sender, EventArgs e)
        {
            if (serialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < serialNo.SelectedItems.Count; i++)
                {
                    selectedSerial.Add(serialNo.SelectedItems[i].ToString());                    
                }
                for (int i = serialNo.SelectedItems.Count - 1; i >= 0 ; i--)
                {                    
                    serialList.Remove(serialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }            
        }

        /////////////////////////////
        /// Deselect some serial
        /////////////////////////////
        private void buttonDeselect_Click(object sender, EventArgs e)
        {
            if (selectedSerialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < selectedSerialNo.SelectedItems.Count; i++)
                {
                    serialList.Add(selectedSerialNo.SelectedItems[i].ToString());
                }
                for (int i = selectedSerialNo.SelectedItems.Count - 1; i >= 0; i--)
                {
                    selectedSerial.Remove(selectedSerialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }
        }
    }
}
